#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# new Env("优智云家")
# cron: 0 8 * * *
✦ 小程序信息    ▸ 名称：优智云家品牌商城
▸ 类别：积分换实物
▸ 可换种类：数码类（200积分起换）
✦ 执行说明    ▸ 首次执行需手动进入小程序完成手机号绑定
▸ 每日自动执行签到任务
✦ 环境变量    ▸ Applet_YZJ_Wxid: 指定允许执行的账号(Wxid)，多个用英文逗号分隔
"""
import time
import json
import os
import requests
from typing import Optional, Dict, Any
from requests.exceptions import RequestException

class YouzhiyunjiaSignin:
    def __init__(self):
        self.base_url = "https://xapi.weimob.com"
        self.app_id = "wxa61f98248d20178b"
        self.client = requests.Session()
        self.headers = {
            "Host": "xapi.weimob.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf2540611) XWEB/14199",
            "Content-Type": "application/json",
            "Accept": "*/*",
            "Referer": "https://servicewechat.com/wxa61f98248d20178b/81/page-frame.html",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        self.token = None
        
        # 协议服务配置
        proxy = os.getenv("API_PROXY", "192.168.0.183:5000").strip()
        if not proxy.startswith(("http://", "https://")):
            proxy = f"http://{proxy}"
        self.local_proxy = proxy
        self.retry_times = 3

    def get_wx_list(self):
        """获取微信账户列表"""
        url = f"{self.local_proxy}/getallwx"
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json()
            print(f"获取微信列表失败: HTTP {response.status_code}")
        except RequestException as e:
            print(f"获取微信列表失败: {str(e)}")
        return []

    def get_wx_code(self, wxid: str) -> Optional[str]:
        """获取小程序登录凭证"""
        url = f"{self.local_proxy}/loginbyapp?Wxid={wxid}&appid={self.app_id}"
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json().get("code")
            print(f"获取wxCode失败: HTTP {response.status_code}")
        except RequestException as e:
            print(f"获取wxCode失败: {str(e)}")
        return None

    def login(self, wxid: str) -> bool:
        """用户登录"""
        code = self.get_wx_code(wxid)
        if not code:
            print("获取微信登录code失败")
            return False

        payload = {
            "appid": self.app_id,
            "basicInfo": {
                "bosId": "4022115200359",
                "cid": "821033359",
                "tcode": "weimob",
                "vid": "6016741943359"
            },
            "env": "production",
            "extendInfo": {"source": 1},
            "is_pre_fetch_open": True,
            "parentVid": 0,
            "pid": "",
            "storeId": "",
            "code": code,
            "queryAuthConfig": True
        }
        
        url = f"{self.base_url}/fe/mapi/user/loginX"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get("errcode") == 0:
                token = data.get("data", {}).get("token")
                if token:
                    self.token = token
                    self.headers["x-wx-token"] = token
                    print("登录成功")
                    return True
                print("登录失败：未获取到token")
            else:
                print(f"登录失败：{data.get('errmsg', '未知错误')}")
        except Exception as e:
            print(f"登录请求失败: {e}")
        return False

    def check_signin_status(self) -> Optional[bool]:
        """检查签到状态"""
        payload = {
            "appid": self.app_id,
            "basicInfo": {
                "vid": 6016741943359,
                "vidType": 2,
                "bosId": 4022115200359,
                "productId": 146,
                "productInstanceId": 15532102359,
                "productVersionId": "10003",
                "merchantId": 2000230069359,
                "tcode": "weimob",
                "cid": 821033359
            },
            "extendInfo": {
                "wxTemplateId": 7930,
                "analysis": [],
                "bosTemplateId": 1000001998,
                "childTemplateIds": [
                    {"customId": 90004, "version": "crm@0.1.64"},
                    {"customId": 90002, "version": "ec@69.1"},
                    {"customId": 90006, "version": "hudong@0.0.229"},
                    {"customId": 90008, "version": "cms@0.0.506"}
                ],
                "quickdeliver": {"enable": True},
                "youshu": {"enable": False},
                "source": 1,
                "channelsource": 5,
                "refer": "onecrm-signgift",
                "mpScene": 1035
            },
            "queryParameter": None,
            "i18n": {"language": "zh", "timezone": "8"},
            "pid": "",
            "storeId": "",
            "customInfo": {"source": 0, "wid": 11659047914}
        }
        
        url = f"{self.base_url}/api3/onecrm/mactivity/sign/misc/sign/activity/c/signMainInfo"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get("errcode") == "0":
                has_sign = data.get("data", {}).get("hasSign", False)
                print(f"签到状态: {'已签到' if has_sign else '未签到'}")
                return has_sign
            print(f"检查签到状态失败：{data.get('errmsg', '未知错误')}")
        except Exception as e:
            print(f"检查签到状态请求失败: {e}")
        return None

    def submit_signin(self) -> Optional[Dict[str, Any]]:
        """提交签到"""
        payload = {
            "appid": self.app_id,
            "basicInfo": {
                "vid": 6016741943359,
                "vidType": 2,
                "bosId": 4022115200359,
                "productId": 146,
                "productInstanceId": 15532102359,
                "productVersionId": "10003",
                "merchantId": 2000230069359,
                "tcode": "weimob",
                "cid": 821033359
            },
            "extendInfo": {
                "wxTemplateId": 7930,
                "analysis": [],
                "bosTemplateId": 1000001998,
                "childTemplateIds": [
                    {"customId": 90004, "version": "crm@0.1.64"},
                    {"customId": 90002, "version": "ec@69.1"},
                    {"customId": 90006, "version": "hudong@0.0.229"},
                    {"customId": 90008, "version": "cms@0.0.506"}
                ],
                "quickdeliver": {"enable": True},
                "youshu": {"enable": False},
                "source": 1,
                "channelsource": 5,
                "refer": "onecrm-signgift",
                "mpScene": 1035
            },
            "queryParameter": None,
            "i18n": {"language": "zh", "timezone": "8"},
            "pid": "",
            "storeId": "",
            "customInfo": {"source": 0, "wid": 11659047914}
        }
        
        url = f"{self.base_url}/api3/onecrm/mactivity/sign/misc/sign/activity/core/c/sign"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get("errcode") == "0":
                print("签到成功")
                return data.get("data", {})
            print(f"签到失败：{data.get('errmsg', '未知错误')}")
        except Exception as e:
            print(f"签到请求失败: {e}")
        return None

    def get_account_info(self) -> Optional[int]:
        """获取账号积分信息"""
        payload = {
            "appid": self.app_id,
            "basicInfo": {
                "vid": 6016741943359,
                "vidType": 2,
                "bosId": 4022115200359,
                "productId": 1,
                "productInstanceId": 15532140359,
                "productVersionId": "32049",
                "merchantId": 2000230069359,
                "tcode": "weimob",
                "cid": 821033359
            },
            "extendInfo": {
                "wxTemplateId": 7930,
                "analysis": [],
                "bosTemplateId": 1000001998,
                "childTemplateIds": [
                    {"customId": 90004, "version": "crm@0.1.64"},
                    {"customId": 90002, "version": "ec@69.1"},
                    {"customId": 90006, "version": "hudong@0.0.229"},
                    {"customId": 90008, "version": "cms@0.0.506"}
                ],
                "quickdeliver": {"enable": True},
                "youshu": {"enable": False},
                "source": 1,
                "channelsource": 5,
                "refer": "cms-usercenter",
                "mpScene": 1035
            },
            "queryParameter": None,
            "i18n": {"language": "zh", "timezone": "8"},
            "pid": "",
            "storeId": "",
            "targetBasicInfo": {
                "productInstanceId": 15532102359
            },
            "request": {}
        }
        
        url = f"{self.base_url}/api3/onecrm/point/myPoint/getSimpleAccountInfo"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get("errcode") == "0":
                points = data.get("data", {}).get("sumAvailablePoint", 0)
                print(f"当前积分: {points}")
                return points
            print(f"获取积分失败：{data.get('errmsg', '未知错误')}")
        except Exception as e:
            print(f"获取积分请求失败: {e}")
        return None

    def process_account(self, wx_account: dict) -> bool:
        """处理单个账号"""
        wxid = wx_account.get("Wxid")
        wxname = wx_account.get("wxname", "未知用户")
        print(f"\n处理账号: {wxname} (Wxid: {wxid})")

        if not self.login(wxid):
            print(f"{wxname} 登录失败")
            return False

        sign_status = self.check_signin_status()
        if sign_status is None:
            print(f"{wxname} 检查签到状态失败")
            return False

        if not sign_status:
            reward_data = self.submit_signin()
            if reward_data is None:
                print(f"{wxname} 签到失败")
                return False
        
        self.get_account_info()
        return True

def main():
    print("="*50)
    print("优智云家品牌商城小程序签到")
    print("="*50)
    
    signin = YouzhiyunjiaSignin()
    print(f"协议服务地址: {signin.local_proxy}")
    
    # 获取允许的账号列表
    allowed_wxids = [x.strip() for x in os.getenv("Applet_YZJ_Wxid", "").split(",") if x.strip()]
    if allowed_wxids:
        print(f"允许的Wxid: {', '.join(allowed_wxids)}")
    else:
        print("未设置Applet_YZJ_Wxid环境变量，将处理所有账号")
    
    wx_accounts = signin.get_wx_list()
    if not wx_accounts:
        print("未获取到任何在线账号")
        return

    print(f"获取到 {len(wx_accounts)} 个账号")
    
    # 过滤账号 - 只允许指定的Wxid
    if allowed_wxids:
        filtered_accounts = [acc for acc in wx_accounts if acc.get("Wxid") in allowed_wxids]
        print(f"根据Applet_YZJ_Wxid过滤后，需要处理 {len(filtered_accounts)} 个账号")
    else:
        filtered_accounts = wx_accounts
        print("未设置Applet_YZJ_Wxid，处理所有账号")
    
    if not filtered_accounts:
        print("没有符合条件的账号需要处理")
        return
    
    for i, account in enumerate(filtered_accounts, 1):
        print(f"\n{'='*50}")
        print(f"处理第 {i}/{len(filtered_accounts)} 个账号: {account.get('wxname')} (Wxid: {account.get('Wxid')})")
        print(f"{'='*50}")
        try:
            signin.process_account(account)
        except Exception as e:
            print(f"处理账号时发生错误: {e}")
        
        if i < len(filtered_accounts):
            print("等待2秒...")
            time.sleep(2)
    
    print("\n所有账号处理完成")

if __name__ == "__main__":
    main()